//
//  RxCocoa+.swift
//  suda
//
//  Created by youai on 2019/7/30.
//  Copyright © 2019年 youi. All rights reserved.
//

import Foundation
import RxSwift
import RxCocoa

extension ObservableType {
    
    /**
     以弱引用的方式绑定对象（避免[weak self]的写法），建立闭包，以闭包进行订阅
     有参数版本
     - Parameters:
         - target: 弱引用的对象，也就是 [weak self]的self
         - disposeWith: 如果该值为true而且target是NSObject，则加入takeUntil(target.rx.deallocated)，默认为true
         - closure: 回调闭包, 参数为 订阅的消息，target
     */
    @discardableResult
    public func bindWeak<T:AnyObject>(_ target:T,disposeWith:Bool=true,closure:@escaping (_ element:Self.Element,_ target:T)->()) -> Disposable {
        let weakTarget = WeakReference<T>(target: target)
        let closure : (Self.Element)->() = { param in
            if let target = weakTarget.target {
                closure(param,target)
            }
        }
        if disposeWith,let nsobj = target as? NSObject {
            return takeUntil(nsobj.rx.deallocated).bind(onNext: closure)
        }
        return bind(onNext: closure)
    }
    
    /**
     以弱引用的方式绑定对象（避免[weak self]的写法），建立闭包，以闭包进行订阅
     无参数版本
     - Parameters:
     - target: 弱引用的对象，也就是 [weak self]的self
     - disposeWith: 如果该值为true而且target是NSObject，则加入takeUntil(target.rx.deallocated)，默认为true
     - closure: 回调闭包，参数为 target
     */
    @discardableResult
    public func bindWeak<T:AnyObject>(_ target:T,disposeWith:Bool=true,closure:@escaping (_ target:T)->()) -> Disposable {
        let weakTarget = WeakReference<T>(target: target)
        let closure : (Self.Element)->() = { param in
            if let target = weakTarget.target {
                closure(target)
            }
        }
        if disposeWith,let nsobj = target as? NSObject {
            return takeUntil(nsobj.rx.deallocated).bind(onNext: closure)
        }
        return bind(onNext: closure)
    }
}


extension QuickTableView {
//    func onSelectedObersable() -> Observable<T?> {
//        let selected = rx.itemSelected
//        let selected2 = selected.map {[weak self] (indexPath) -> T? in
//            guard let s = self else {return nil}
//            let idx = indexPath[1]
//            if idx < 0 || idx >= s.list.count {
//                return nil
//            }
//            let data = s.list[idx]
//            return data
//        }
//        return selected2
//    }
    
    func onDataSelectedSubject()->PublishSubject<T> {
        let subject = PublishSubject<T>()
        _ = subject.takeUntil(self.rx.deallocated)
        self.onDataSelected = { data in
            subject.onNext(data)
        }
        return subject
    }
    
    func onSetCellSubject()->PublishSubject<C> {
        let subject = PublishSubject<C>()
        _ = subject.takeUntil(self.rx.deallocated)
        self.onSetCell = { cell in
            subject.onNext(cell)
        }
        return subject
    }
}
